<?php
require_once("mysql.inc.php");

if(isset($_POST["username"]) && isset($_POST["password"])) {

	login($_POST["username"], $_POST["password"]);
}

function login($username, $password) {

	$username = stripslashes(mysql_real_escape_string($username));
	$password = md5(stripslashes(mysql_real_escape_string($password)));
	
	$result = mysql_query("SELECT * FROM `users` WHERE `username`='$username' AND `password`='$password' AND (`role`='Beheerder' OR `role`='TopBeheerder')") 
			  or die(mysql_error());
	$num = mysql_num_rows($result);
	$fetch = mysql_fetch_array($result);
	
	if($num == 0) {
		echo 0;
	}
	else if($num == 1) {
		if($password == $fetch["password"]) {
			startSession($username, $password, $fetch["role"]);
			echo 1;
		}
		else {
			echo 0;
		}
	}
	else {
		echo 2;
	}
}
function startSession($username, $password, $role) {
	
	ob_start();
	
	if(!isset($_SESSION)) {
		session_start();
	}
	
	$_SESSION["username"] = $username;
	$_SESSION["password"] = $password;
	setcookie("role", $role, time()+3600, "/");
	setcookie("cancelUpdate", "0", time()+3600, "/");
	
	ob_end_flush();
}
?>